import { useEffect,useRef,useState } from "react";
export const isFalsy = (value:unknown)=> value === 0 ? false : !value;

export const isVoid = (value:unknown) => value === undefined || value === null || value === '';

//不能表示成object对象，因为我们想要的是个键值对，object可以包括对象、函数等，结构函数没有意义最后返回空对象
export const cleanObject = (object:{[key:string]:unknown})=>{
    // 下面的写法相当于Object.assign({},object)
    const result = {...object};
    Object.keys(result).forEach(key=>{
        const value = result[key];
        if(isVoid(value)){
            delete result[key];
        }
    });
    return result;
}

//自定义Hook，将useEffect 只更新一次（相当于componentDidMount）的情况抽象出来
export const useMount = (callback:Function)=>{
    useEffect(()=>{
        callback();
        //TODO 依赖项里加上callback会造成无限循环，这个和useCallback和useMemo有关系
        //eslint-disable-next-line react-hooks/exhaustive-deps
    },[]);
}

export const useDebounce = <V>(value:V,delay?:number)=>{
    const [debouncedValue,setDebouncedValue] = useState(value);
    useEffect(()=>{
        //每次在value和delay变化以后设置一个定时器
        const timeout = setTimeout(()=>setDebouncedValue(value),delay);
        //return的这个函数上一个useEffect处理完之后再运行
        return ()=>clearTimeout(timeout)
    },[value,delay]);

    return debouncedValue;
}

export const useArray = <T>(initialArray:T[])=>{
    const [value,setValue] = useState(initialArray);

    return {
        value,
        setValue,
        add:(item:T)=>setValue([...value,item]),
        clear:()=>setValue([]),
        removeIndex:(index:number)=>{
            let copy = [...value];
            copy.splice(index,1);
            setValue(copy);
        }
    }
}

// export const useDocumentTitle = (title:string,keepOnUnmount:boolean=true)=>{
//     //页面加载时：oldTitle === 旧title react app
//     //页面加载后，调用useEffect更新了title，组件再渲染的话 oldTitle === 新title
//     const oldTitle = document.title;

//     useEffect(()=>{
//         document.title = title;
//     },[title]);

//     //只在加载时调用一次，通过闭包保存了旧title
//     useEffect(()=>{
//         return ()=>{
//             if(!keepOnUnmount){
//                 document.title = oldTitle;
//             }
//         }
//     },[]);
// }

export const useDocumentTitle = (title:string,keepOnUnmount:boolean=true)=>{
    const oldTitle = useRef(document.title).current;

    useEffect(()=>{
        document.title = title;
    },[title]);

    //只在加载时调用一次，通过闭包保存了旧title
    useEffect(()=>{
        return ()=>{
            if(!keepOnUnmount){
                document.title = oldTitle;
            }
        }
        //eslint-disable-next-line react-hooks/exhaustive-deps
    },[keepOnUnmount,title]);
}

export const resetRoute = ()=>window.location.href = window.location.origin;

export const useMountedRef = ()=>{
    const mountedRef = useRef(false);
    useEffect(()=>{
        mountedRef.current = true;
        return()=>{
            mountedRef.current = false;
        }
    });
    return mountedRef;
}